<?php
namespace app\common\service;

use app\common\util\Util;
use think\Model;

class WxMassSendingService extends BaseService
{

    /**
     * @param $sid
     * @param array $postParam
     * @return array
     * @throws \think\Exception
     * 新增或修改群发内容
     */
    public function saveContent($sid, $postParam = []){
        $mid = $postParam['mid'] ?? 0;

        $save_data = [];
        $save_data['title'] = $postParam['title'];
        $save_data['message_type'] = $postParam['message_type'];
        $save_data['res_id'] = $postParam['message_type'] == 1 ? 0 : $postParam['res_id'];
        $save_data['content'] = $postParam['message_type'] == 1 ? $postParam['content'] : '';
        $save_data['send_time'] = time();
        $save_data['status'] = 0;

        if($mid == 0){
            //新增
            $save_data['sid'] = $sid;
            $result = db('mass_send')->insert($save_data);
        } else {
            //更新
            $result = db('mass_send')->where(['id' => $mid, 'sid' => $sid])->update($save_data);
        }
        if($result !== false){
            return ['status' => 1, 'msg' => '保存成功'];
        } else {
            return ['status' => 0, 'msg' => '保存失败'];
        }

    }

    /**
     * @param $sid
     * @param $mid
     * @return array|bool|false|\PDOStatement|string|Model
     * 获取群发记录详情
     */
    public function getDetail($sid, $mid){
        $detail = db('mass_send')->field('id as mid,sid,title,message_type,content,res_id')->where(['sid' => $sid, 'id' => $mid])->find();
        if(empty($detail)){
            return false;
        }
        if($detail['message_type'] == 2 || $detail['message_type'] == 3){
            $res = db('res')->where(['res_id' => $detail['res_id']])->find();

            $res_temp = $res['res'];
            $res_temp = str_replace(PHP_EOL, "", $res_temp);
            $temp = json_decode($res_temp, true);
            $detail['content'] = [
                'res_id' => $res['res_id'],
                'title' => $temp['title'],
                'create_time' => date('Y-m-d H:i:s', $res['create_time']),
                'coverimg' => $temp['coverimg'],
                'summary' => $temp['summary'] ?? '',
                'type' => $res['type'],
                'dataset' => $temp['dataset'] ?? ''
            ];
        }

        return ['content' => $detail];
    }

    /**
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     * 获取群发记录列表
     */
    public function getList($sid, $p, $pageSize){
        $field = 'id,title,send_time,explain,weixin_sendcount,status';
        $list_count = db('mass_send')->where(['sid' => $sid])->count();
        $list = db('mass_send')->field($field)->where(['sid' => $sid])->order('send_time desc')->limit(($p-1)*$pageSize, $pageSize)->select();
        if($list){
            foreach($list as $k => $v){
                $list[$k]['send_time'] = date('Y-m-d H:i:s', $v['send_time']);
            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    /**
     * 给管理员发送预览群发内容
     * @param $sid
     * @param array $postParam
     * @return array
     */
    public function sendToAdmin($sid, $postParam = []){
        //查询是否存在管理员
        $admin = db('user_integral')->field('userid,touser')->where(['sid' => $sid, 'is_administrator' => 1])->find();
        if(empty($admin)){
            return ['status' => 0, 'msg' => '请先设置管理员'];
        }

        //图文类型
        $message_type = $postParam['message_type'];

        if($message_type == 1){
            //文本
            $msgtype = 'text';
            $message = strip_tags(html_entity_decode($postParam['content']));

        } else {
            //图文
            //消息类型  easywechat中为news，微信官方接口为mpnews
            $msgtype = 'news';
            $res_id = $postParam['res_id'];
            $materialService = new MaterialService();

            //上传图文
            $upload_result = $materialService->uploadMaterial($sid, $res_id);
            if(isset($upload_result['status']) && $upload_result['status'] == 0){
                return ['status' => 0, 'msg' => $upload_result['msg']];
            }

            //图文则传入media_id
            $message = $upload_result['media_id'];
        }
        //调用预览接口
        $wxService = new WeixinService();
        $result = $wxService->preview($sid, $msgtype, $message, $admin['touser']);

        $result =  json_decode($result,1);
        if($result['errcode'] != 0){
            $err_msg = Util::get_error($result['errcode']);
            return ['status' => 0, 'msg' => $result['errcode'] . ':' . $err_msg];
        } else {
            return ['status' => 1, 'msg' => '已发送给管理员，请在手机上预览'];
        }
    }

    /**
     * 群发消息给指定用户
     * @param $sid
     * @param array $postParam
     * @return array
     */
    public function sendToUser($sid, $postParam = []){
        //图文类型
        $message_type = $postParam['message_type'];

        if($message_type == 1){
            //文本
            $msgtype = 'text';
            $message = strip_tags(html_entity_decode($postParam['content']));
        } else {
            $msgtype = 'news';
            $res_id = $postParam['res_id'];
            $materialService = new MaterialService();

            //上传图文
            $upload_result = $materialService->uploadMaterial($sid, $res_id);
            if(isset($upload_result['status']) && $upload_result['status'] == 0){
                return ['status' => 0, 'msg' => $upload_result['msg']];
            }

            //图文则传入media_id
            $message = $upload_result['media_id'];
        }

        $wxService = new WeixinService();

        //获取用户列表
        $user_list = $wxService->get_user_list($sid);
        $users = json_decode($user_list, 1);
        $openIds = $users['data']['openid'];

        //给指定用户群发消息
        $result = $wxService->mass_send($sid, $msgtype, $message, $openIds);
        $result = json_decode($result, 1);

        //记录日志
        $log_data = [];
        $log_data['sid'] = $sid;
        $log_data['title'] = $postParam['title'];
        $log_data['message_type'] = $message_type;
        $log_data['content'] = $postParam['content'] ?? '';
        $log_data['res_id'] = $postParam['res_id'] ?? 0;
        $log_data['fans'] = $users['count'];
        $log_data['send_time'] = time();
        $log_data['explain'] = $result['errmsg'];
        $log_data['msg_id'] = $result['msg_id'];
        //发送返回的状态  1：成功  2：失败
        $log_data['status'] = $result['errcode'] == 0 ? 1 : 2;
        $this->addLog($log_data);

        if($result['errcode'] > 0){
            $err_msg = Util::get_error($result['errcode']);
            return ['status' => 0, 'msg' => $err_msg];
        } else {
            return ['status' => 1, 'msg' => '群发成功'];
        }
    }

    public function addLog($arr = []){
        return db('mass_send')->insert($arr);
    }
}







